var WMIDB;
var DB = {
	initDatabase: function() {
		try {
			if (!window.openDatabase) {
				alert('Local Databases are not supported by your browser. Please use a Webkit browser for this demo');
			} else {
				var shortName = 'WMIDBDREAM_'+localStorage['user_id'];
				var version = '1.0';
				var displayName = 'WMIDBDREAM_'+localStorage['user_id']+' Test';
				var maxSize = 1073741824; // 1GB
				WMIDB = openDatabase(shortName, version, displayName, maxSize);
				DB.createTables();
			}
		} catch(e) {
			if (e == 2) {
				// Version mismatch.
				console.log("Invalid database version.");
			} else {
				console.log("Unknown error "+ e +".");
			}
			return;
		} 
	},
	createTables: function(){
		WMIDB.transaction(
			function (transaction) {
				transaction.executeSql('CREATE TABLE IF NOT EXISTS photos(id INTEGER NOT NULL PRIMARY KEY, base TEXT NOT NULL);', [], DB.nullDataHandler, DB.errorHandler);
				transaction.executeSql('CREATE TABLE IF NOT EXISTS tpl(id INTEGER NOT NULL PRIMARY KEY, message TEXT NOT NULL, photo TEXT NOT NULL, date TEXT NOT NULL);', [], DB.nullDataHandler, DB.errorHandler);
				transaction.executeSql('CREATE TABLE IF NOT EXISTS fav(id INTEGER NOT NULL PRIMARY KEY, name TEXT NOT NULL, age TEXT NOT NULL, id_man TEXT NOT NULL, receiver TEXT NOT NULL);', [], DB.nullDataHandler, DB.errorHandler);
				transaction.executeSql('CREATE TABLE IF NOT EXISTS blist(id INTEGER NOT NULL PRIMARY KEY, id_man TEXT NOT NULL);', [], DB.nullDataHandler, DB.errorHandler);
				transaction.executeSql('CREATE TABLE IF NOT EXISTS blist_chat(id INTEGER NOT NULL PRIMARY KEY, id_man TEXT NOT NULL);', [], DB.nullDataHandler, DB.errorHandler);
				transaction.executeSql('CREATE TABLE IF NOT EXISTS log(id INTEGER NOT NULL PRIMARY KEY, message TEXT NOT NULL, man TEXT NOT NULL, cron TEXT NOT NULL, date TEXT NOT NULL);', [], DB.nullDataHandler, DB.errorHandler);
			}
		);
	},
	nullDataHandler: function(){
		console.log("SQL Query Succeeded");
	},
	errorHandler: function(transaction, error){
		if (error.code==1){
			// DB Table already exists
		} else {
			// Error is a human-readable string.
			console.log('Oops.  Error was '+error.message+' (Code '+error.code+')');
		}
		return false;
	}
}